package com.zgw.his.design.editor;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.wb.internal.core.xml.editor.XmlEditorPage;

/**
 * 模板页面属性设置页
 * 
 * */
public class MedicalPropertyPage extends XmlEditorPage {
	private TemplateInfoComposite infoComposite;
	private final String regex = ",";

	public Control createControl(Composite parent) {
		infoComposite = new TemplateInfoComposite(parent, SWT.NONE,
				(MedicalEditor) m_editor);
		return infoComposite;
	}

	public Control getControl() {
		return infoComposite;
	}

	public String getName() {
		return "页面属性";
	}

	public Image getImage() {
		return null;
	}

	@Override
	public void setActive(boolean active) {
		try {
			if (active) {
				setBoundsText();
			} else {
				setBounds();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.setActive(active);
	}

	private void setBounds() throws Exception {
		MedicalDesignPage xp = (MedicalDesignPage) m_editor.getDesignPage();
		if (xp.getRoot() != null) {
			String bou = xp.getRoot().getElement().getAttribute("bounds");
			String[] bound = bou.split(regex);
			String newW = infoComposite.getWidth().trim();
			String newH = infoComposite.getHeight().trim();
			if (!bound[2].equals(newW) || !bound[3].equals(newH)) {
				bound[2] = newW;
				bound[3] = newH;
				xp.getRoot().startEdit();
				xp.getRoot().getElement()
						.setAttribute("bounds", joinArray(bound));
				xp.getRoot().endEdit();
			}
		}
	}

	private void setBoundsText() {
		MedicalDesignPage xp = (MedicalDesignPage) m_editor.getDesignPage();
		if (xp.getRoot() != null) {
			String bou = xp.getRoot().getElement().getAttribute("bounds");
			String[] bound = bou.split(regex);
			infoComposite.setWidth(bound[2].trim());
			infoComposite.setHeight(bound[3].trim());
			infoComposite.setInput(((MedicalEditor) m_editor)
					.getMedicalTemplate().getData());
		}
	}

	private String joinArray(String[] array) {
		StringBuffer result = new StringBuffer();
		for (String s : array) {
			result.append(regex);
			result.append(s);
		}
		return result.substring(1);
	}
}
